<!--------------------------------
 - @Author: Your Name
 - @LastEditor: Your Name
 - @LastEditTime: 2025-11-07
 - Copyright © 2025 Your Name
 --------------------------------->

<template>
  <CommonPage>
    <template #action>
      <NButton v-permission="'AddS3Config'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        添加S3配置
      </NButton>
    </template>

    <NCard title="S3存储状态" segmented class="mb-12">
      <NGrid :cols="4" :x-gap="12" :y-gap="12">
        <NGridItem>
          <NStatistic label="总配置数" :value="statusData.totalConfigs" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="已启用" :value="statusData.enabledConfigs">
            <template #prefix>
              <NIcon :component="CheckmarkCircle" />
            </template>
          </NStatistic>
        </NGridItem>
        <NGridItem>
          <NStatistic label="已禁用" :value="statusData.disabledConfigs">
            <template #prefix>
              <NIcon :component="CloseCircle" />
            </template>
          </NStatistic>
        </NGridItem>
        <NGridItem>
          <NStatistic label="缓存命中率" :value="cacheData.hitRate">
            <template #suffix>
              %
            </template>
          </NStatistic>
        </NGridItem>
      </NGrid>

      <NGrid :cols="3" :x-gap="12" :y-gap="12" class="mt-12">
        <NGridItem>
          <NStatistic label="缓存大小" :value="cacheData.cacheSize" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="缓存条目" :value="cacheData.cacheEntries" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="最后刷新" :value="formatDateTime(new Date(cacheData.lastRefresh))" />
        </NGridItem>
      </NGrid>
    </NCard>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1400"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="业务类型" :label-width="70">
        <NSelect
          v-model:value="queryItems.businessType"
          :options="businessTypeOptions"
          clearable
          placeholder="请选择业务类型"
        />
      </MeQueryItem>

      <MeQueryItem label="状态" :label-width="70">
        <NSelect
          v-model:value="queryItems.enabled"
          :options="[
            { label: '启用', value: true },
            { label: '禁用', value: false },
          ]"
          clearable
          placeholder="请选择状态"
        />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="700px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="120"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="业务类型"
          path="businessType"
          :rule="{
            required: true,
            message: '请选择业务类型',
            trigger: ['change'],
          }"
        >
          <NSelect
            v-model:value="modalForm.businessType"
            :options="businessTypeOptions"
            :disabled="modalAction === 'edit'"
            placeholder="请选择业务类型"
          />
        </n-form-item>

        <n-form-item
          label="S3端点"
          path="endpoint"
          :rule="{
            required: true,
            message: '请输入S3端点',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.endpoint" placeholder="请输入S3端点URL" />
        </n-form-item>

        <n-form-item
          label="访问密钥"
          path="accessKey"
          :rule="{
            required: true,
            message: '请输入访问密钥',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.accessKey"
            type="password"
            show-password-on="mousedown"
            placeholder="请输入访问密钥"
          />
        </n-form-item>

        <n-form-item
          label="私密密钥"
          path="secretKey"
          :rule="{
            required: true,
            message: '请输入私密密钥',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input
            v-model:value="modalForm.secretKey"
            type="password"
            show-password-on="mousedown"
            placeholder="请输入私密密钥"
          />
        </n-form-item>

        <n-form-item
          label="存储桶"
          path="bucket"
          :rule="{
            required: true,
            message: '请输入存储桶名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.bucket" placeholder="请输入存储桶名称" />
        </n-form-item>

        <n-form-item label="基础路径" path="basePath">
          <n-input v-model:value="modalForm.basePath" placeholder="请输入基础路径，如：idp-prototype/" />
        </n-form-item>

        <n-form-item label="区域" path="region">
          <n-input v-model:value="modalForm.region" placeholder="请输入区域，如：cn-north-1" />
        </n-form-item>

        <n-form-item label="描述" path="description">
          <n-input
            v-model:value="modalForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入配置描述"
          />
        </n-form-item>

        <n-form-item label="路径风格访问" path="pathStyle">
          <NSwitch v-model:value="modalForm.pathStyle">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              禁用
            </template>
          </NSwitch>
        </n-form-item>

        <n-form-item label="是否启用" path="enabled">
          <NSwitch v-model:value="modalForm.enabled">
            <template #checked>
              启用
            </template>
            <template #unchecked>
              禁用
            </template>
          </NSwitch>
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { CheckmarkCircle, CloseCircle } from '@vicons/ionicons5'
import { NButton, NCard, NGrid, NGridItem, NIcon, NSelect, NStatistic, NSwitch } from 'naive-ui'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { formatDateTime } from '@/utils'
import api from './api'

defineOptions({ name: 'S3StorageMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

// 业务类型选项
const businessTypeOptions = ref([
  { label: '原型文件', value: 'prototype' },
  { label: '图床图片', value: 'image' },
  { label: '项目文档', value: 'document' },
  { label: '用户头像', value: 'avatar' },
  { label: '其他', value: 'other' },
])

// 状态数据
const statusData = ref({
  totalConfigs: 0,
  enabledConfigs: 0,
  disabledConfigs: 0,
})

// 缓存数据
const cacheData = ref({
  cacheSize: '0 MB',
  cacheEntries: 0,
  hitRate: '0',
  lastRefresh: new Date().toISOString(),
})

onMounted(() => {
  $table.value?.handleSearch()
  loadStatusData()
  loadCacheData()
})

// 加载状态数据
async function loadStatusData() {
  try {
    const result = await api.getConfigStatus()
    statusData.value = result.data
  }
  catch (error) {
    console.error('加载状态数据失败:', error)
  }
}

// 加载缓存数据
async function loadCacheData() {
  try {
    const result = await api.getCacheStatus()
    cacheData.value = result.data
  }
  catch (error) {
    console.error('加载缓存数据失败:', error)
  }
}

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: 'S3配置',
  initForm: {
    enabled: true,
    pathStyle: false,
    businessType: null, // 初始化为null，需要用户选择
  },
  doCreate: api.create,
  doDelete: api.delete,
  doUpdate: api.update,
  refresh: async () => {
    await $table.value?.handleSearch()
    await loadStatusData()
    await loadCacheData()
  },
})

const columns = [
  {
    title: '业务类型',
    key: 'businessType',
    width: 150,
    ellipsis: { tooltip: true },
    render: (row) => {
      const option = businessTypeOptions.value.find(opt => opt.value === row.businessType)
      return option ? option.label : row.businessType
    },
  },
  {
    title: 'S3端点',
    key: 'endpoint',
    width: 200,
    ellipsis: { tooltip: true },
  },
  {
    title: '存储桶',
    key: 'bucket',
    width: 150,
    ellipsis: { tooltip: true },
  },
  {
    title: '基础路径',
    key: 'basePath',
    width: 150,
    ellipsis: { tooltip: true },
  },
  {
    title: '区域',
    key: 'region',
    width: 120,
    ellipsis: { tooltip: true },
  },
  {
    title: '描述',
    key: 'description',
    width: 200,
    ellipsis: { tooltip: true },
  },
  {
    title: '状态',
    key: 'enabled',
    width: 100,
    render: row =>
      h(
        NSwitch,
        {
          size: 'small',
          rubberBand: false,
          value: row.enabled,
          loading: !!row.enableLoading,
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '禁用',
        },
      ),
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(row.createTime))
    },
  },
  {
    title: '路径风格访问',
    key: 'pathStyle',
    width: 120,
    render: (row) => {
      return h(
        NSwitch,
        {
          size: 'small',
          rubberBand: false,
          value: row.pathStyle,
          loading: !!row.pathStyleLoading,
          onUpdateValue: () => handlePathStyleChange(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '禁用',
        },
      )
    },
  },
  {
    title: '更新时间',
    key: 'updateTime',
    width: 180,
    render(row) {
      return h('span', formatDateTime(row.updateTime))
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 300,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            class: 'ml-12px',
            onClick: () => handleTest(row),
          },
          {
            default: () => '测试',
            icon: () => h('i', { class: 'i-carbon:test-tube text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            class: 'ml-12px',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-material-symbols:edit-outline text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

async function handleEnable(row) {
  row.enableLoading = true
  try {
    await api.update({ id: row.id, enabled: !row.enabled })
    row.enableLoading = false
    $message.success('操作成功')
    await loadStatusData()
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.enableLoading = false
  }
}

async function handlePathStyleChange(row) {
  row.pathStyleLoading = true
  try {
    await api.update({ id: row.id, pathStyle: !row.pathStyle })
    row.pathStyleLoading = false
    $message.success('操作成功')
    await loadStatusData()
    $table.value?.handleSearch()
  }
  catch (error) {
    console.error(error)
    row.pathStyleLoading = false
  }
}

function handleEdit(row) {
  handleOpen({ action: 'edit', title: '编辑S3配置', row })
}

async function handleTest(row) {
  try {
    const result = await api.testConfig(row.id)
    $message.success(`测试成功: ${result.data.message}`)
    console.log('测试结果:', result.data)
  }
  catch (error) {
    $message.error(`测试失败: ${error.message}`)
    console.error('测试失败:', error)
  }
}
</script>
